package com.chen.blue;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

/**
 * @Version v1.0
 * @DateTime 2024/8/16 22:58
 * @Description TODO
 * @Author 一见如初
 */
@Component
@Slf4j
public class RedisAutoStartConfig {


    @PostConstruct
    public static void initRedis() {
        log.info("开始检查系统环境...");
        ProcessBuilder processBuilder = new ProcessBuilder("redis-cli", "ping");
        try {
            Process process = processBuilder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            // 读取命令输出
            StringBuilder output = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }
            // 等待进程结束
            int exitCode = process.waitFor();
            if (exitCode == 0 && output.toString().contains("PONG")) {
                log.info("redis已开启");
            } else {
                // 启动 Redis
                // 根据实际情况修改路径
                ProcessBuilder redisProcess = new ProcessBuilder("redis-server");
                Process start = redisProcess.start();
                // 设置10秒启动时间 超时则认为启动失败
                boolean started = start.waitFor(10, TimeUnit.SECONDS);
                // 这里改一下 一直
                if (start.isAlive()) {
                    log.info("自动启动本机redis");
                } else {
                    log.error("无法启动 Redis");
                    throw new InterruptedException("无法启动 Redis");
                }
            }
        } catch (IOException e) {
            log.error("redis未开启");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }


    }

}
